<template>
  <!-- 公文管理 -->
  <div class="pro_document_response.data.records">
    <div style="padding: 10px; background: #fff">
      <el-card>
        <!-- 查询区域 -->
        <el-button
          style="margin-right: 6px"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="add"
          >新增</el-button
        >
        <el-input
          v-model="searchForm.name"
          placeholder="请输入公文标题"
          style="width: 150px; margin-left: 8px"
          clearable
        ></el-input>
        <el-select
          v-model="searchForm.type"
          placeholder="发文类别"
          style="width: 150px; margin-left: 8px"
          filterable
          clearable
        >
          <el-option
            v-for="item in addDialog.types"
            :key="item.type"
            :value="item.type"
            :label="item.type"
          />
        </el-select>
        <el-select
          v-model="searchForm.security"
          placeholder="安全权限"
          style="width: 150px; margin-left: 8px"
          filterable
          clearable
        >
          <el-option
            v-for="item in addDialog.securities"
            :key="item.security"
            :value="item.security"
            :label="item.security"
          />
        </el-select>
        <el-select
          v-model="searchForm.department"
          placeholder="发文部门"
          style="width: 150px; margin-left: 8px"
          filterable
          clearable
        >
          <el-option
            v-for="item in addDialog.departments"
            :key="item.department"
            :value="item.department"
            :label="item.department"
          />
        </el-select>
        <el-date-picker
          style="margin: 8px"
          v-model="searchTime"
          unlink-panels
          value-format="timestamp"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-button
          style="margin-right: 6px"
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="toSearch"
          >查询</el-button
        >
        <!-- 数据展示区域 -->
        <a-table
          :bordered="true"
          style="margin-top: 10px"
          :data-source="documents"
          size="small"
          :loading="loading"
          :pagination="pagination"
          :rowKey="(record) => record.id"
          :scroll="documents.length > 0 ? { x: 1700 } : {}"
        >
          <a-table-column :width="50" title="序号" align="center">
            <template slot-scope="text, record, index">
              {{ index + 1 }}
            </template>
          </a-table-column>
          <a-table-column
            :width="400"
            key="name"
            title="公文标题"
            data-index="name"
            ellipsis="true"
            align="center"
          />
          <a-table-column
            :width="150"
            key="type"
            title="类别"
            data-index="type"
            ellipsis="true"
            align="center"
          />
          <a-table-column
            :width="100"
            key="security"
            title="安全权限"
            data-index="security"
            ellipsis="true"
            align="center"
          />
          <a-table-column
            :width="100"
            key="fileNo"
            title="档案号"
            data-index="fileNo"
            ellipsis="true"
            align="center"
          />
          <a-table-column
            :width="100"
            key="department"
            title="发文部门"
            data-index="department"
            ellipsis="true"
            align="center"
          />
          <a-table-column
            :width="115"
            key="fileId"
            title="发文"
            data-index="fileId"
            ellipsis="true"
            align="center"
          >
            <template slot-scope="text, record">
              <el-tag
                type="info"
                v-if="record.url === null || record.url === ''"
                >无文件</el-tag
              >
              <el-button
                type="primary"
                v-else
                plain
                size="mini"
                @click="viewFile(record.url)"
                >查看</el-button
              >
            </template>
          </a-table-column>
          <a-table-column
            :width="115"
            key="status"
            title="发文状态"
            data-index="status"
            ellipsis="true"
            align="center"
          >
            <template slot-scope="text">
              <el-tag type="warning" v-if="text === 0">未发文</el-tag>
              <el-tag type="success" v-if="text === 1">已发文</el-tag>
              <el-tag type="info" v-if="text === 2">已撤销</el-tag>
            </template>
          </a-table-column>
          <a-table-column
            key="operatorTime"
            title="新建时间"
            data-index="operatorTime"
            ellipsis="true"
            align="center"
          >
            <template slot-scope="text, record">
              {{ dateTimeFormat(record.operatorTime) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" align="center" fixed="right">
            <!-- scope.status == 1 || scope.url === null || scope.url === '' -->
            <template slot-scope="text, scope, index">
              <el-button
                type="primary"
                size="mini"
                :disabled="scope.status == 1 ? true : false"
                @click="updateDocumentStatus(scope)"
                >发文</el-button
              >
              <el-button
                type="info"
                size="mini"
                :disabled="scope.status == 1 ? false : true"
                @click="updateDocumentStatus(scope)"
                >撤销</el-button
              >
              <el-button
                type="success"
                size="mini"
                :disabled="scope.status == 1 ? true : false"
                @click="showUpdateDialog(scope, index)"
                :loading="uploadLoading[index]"
                >修改</el-button
              >
              <el-button
                type="danger"
                size="mini"
                :disabled="scope.status == 1 ? true : false"
                @click="deleteDocument(scope)"
                >删除</el-button
              >
            </template>
          </a-table-column>
        </a-table>
      </el-card>
    </div>
    <!-- 新增、修改发文-模态框 -->
    <el-dialog v-el-drag-dialog :title="addDialog.title" :visible.sync="addDialog.visible" :close-on-click-modal="false">
      <el-form
        :rules="addFormRules"
        ref="addFormRef"
        :model="addDialog.addForm"
        status-icon
      >
        <el-form-item label="标题" label-width="80px" size="small" prop="name">
          <el-input type="text" v-model="addDialog.addForm.name"></el-input>
        </el-form-item>
        <el-form-item
          label="档案号"
          label-width="80px"
          size="small"
          prop="fileNo"
        >
          <el-input type="text" v-model="addDialog.addForm.fileNo"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="发文类别"
              label-width="80px"
              size="small"
              prop="type"
            >
              <el-select
                v-model="addDialog.addForm.typeId"
                placeholder="请选择"
                size="small"
              >
                <el-option
                  v-for="item in addDialog.types"
                  :key="item.id"
                  :value="item.id"
                  :label="item.type"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="安全权限"
              label-width="80px"
              size="small"
              prop="security"
            >
              <el-select
                v-model="addDialog.addForm.securityId"
                placeholder="请选择"
                size="small"
              >
                <el-option
                  v-for="item in addDialog.securities"
                  :key="item.id"
                  :value="item.id"
                  :label="item.security"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="优先级"
              label-width="80px"
              size="small"
              prop="level"
            >
              <el-select
                v-model="addDialog.addForm.levelId"
                placeholder="请选择"
                size="small"
              >
                <el-option
                  v-for="item in addDialog.levels"
                  :key="item.id"
                  :value="item.id"
                  :label="item.level"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="发文部门"
              label-width="80px"
              size="small"
              prop="department"
            >
              <el-select
                v-model="addDialog.addForm.departmentId"
                placeholder="请选择"
                size="small"
              >
                <el-option
                  v-for="item in addDialog.departments"
                  :key="item.id"
                  :value="item.id"
                  :label="item.department"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div>
          <common-upload
            :maxCount="1"
            :multiple="false"
            :isDragger="false"
            :url="fileUploadUrl"
            v-model="addDialog.fileList"
          />
        </div>
      </el-form>
      <!-- 新增发文-模态框-按钮区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取 消</el-button>
        <el-button
          type="primary"
          :loading="addDialog.addSubmitLoading"
          size="small"
          @click="addSubmit('form')"
          >提 交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import "@/styles/auto-style.css";
import { dateTimeFormat, nullFormat } from "@/utils/format";
import {
  getAction,
  postActionByJson,
  postActionByQueryString,
} from "@/api/manage";
import { beforeUpload, uploadStatusChange } from "@/utils/upload";
import elDragDialog from "@/directive/el-drag-dialog";
import CommonUpload from "@/components/Upload/CommonUpload";

const fileUploadUrl = process.env.VUE_APP_BASE_API + "file/uploadCache";

export default {
  directives: { elDragDialog },
  components: { CommonUpload },
  data() {
    return {
      url: {
        // 查询所有 有效 -- 新增使用
        findAllType: "/document/type/selectAllType",
        findAllSecurity: "/document/security/selectAllSecurity",
        findAllLevel: "/document/level/selectAllLevel",
        findAllDepartment: "/document/department/selectAllDepartment",
        // 查询所有 有效 无效 -- 条件查询使用
        findAllTypeExist: "/document/type/selectAllTypeExist",
        findAllSecurityExist: "/document/security/selectAllSecurityExist",
        findAllLevelExist: "/document/level/selectAllLevelExist",
        findAllDepartmentExist: "/document/department/selectAllDepartmentExist",
        insertDocument: "/document/insertDocument",
        updateDocument: "/document/updateDocument",
        selectDocumentsByParams: "/document/selectDocumentsByParams",
        updateDocumentStatus: "/document/updateDocumentStatus",
        deleteDocument: "/document/deleteDocument",
        selectFileByOtherId: "/file/findByOtherId",
      },
      searchTime: [], // 用来接收查询时间
      searchForm: {},
      documents: [],
      addDialog: {
        addForm: {},
        closeFrom: {}, // 点击取消时，将原来的数据复原
        title: "",
        visible: false,
        types: [],
        levels: [],
        departments: [],
        securities: [],
        fileList: [],
        addSubmitLoading: false,
      },
      loading: true,
      uploadLoading: [],
      fileUploadUrl,
      pagination: {
        showTotal: (total) => `共 ${total} 条结果`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["1", "2", "5", "10"],
        pageNum: 1,
        pageSize: 10,
        total: 0,
        onChange: (pageNum) => {
          this.pagination.pageNum = pageNum;
          this.toSearch();
        },
        onShowSizeChange: (pageNum, pageSize) => {
          this.pagination.pageSize = pageSize;
          this.toSearch();
        }, // 改变每页数量时更新显示
      },
      addFormRules: {
        name: [{ required: true, message: "请输入标题", trigger: "blur" }],
        fileNo: [{ required: true, message: "请输入档案号", trigger: "blur" }],
        typeId: [
          { required: true, message: "请选择发文类别", trigger: "blur" },
        ],
        securityId: [
          { required: true, message: "请选择安全权限", trigger: "blur" },
        ],
        levelId: [{ required: true, message: "请选择优先级", trigger: "blur" }],
        departmentId: [
          { required: true, message: "请选择发文部门", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.toSearch();
    this.selectTypes();
    this.selectSecurities();
    this.selectLevels();
    this.selectDepartments();
  },
  methods: {
    closeDialog() {
      this.addDialog.addForm = this.addDialog.closeFrom;
      this.addDialog.visible = false;
    },
    viewFile(url) {
      if (url) {
        window.open(url);
      } else {
        this.$message.warning("未上传发文！");
      }
    },
    beforeUpload,
    uploadStatusChange,
    toSearch() {
      if (this.searchTime) {
        this.searchForm.startTime = this.searchTime[0];
        this.searchForm.endTime = this.searchTime[1];
      } else {
        this.searchForm.startTime = "";
        this.searchForm.endTime = "";
      }
      this.searchForm.pageNum = this.pagination.pageNum;
      this.searchForm.pageSize = this.pagination.pageSize;
      getAction(this.url.selectDocumentsByParams, this.searchForm)
        .then((resp) => {
          this.documents = resp.data.records;
          this.pagination.pageSize = parseInt(resp.data.size);
          this.pagination.total = parseInt(resp.data.total);
          this.loading = false;
          console.log(this.documents);
        })
        .catch((item) => {
          console.log(item);
          this.loading = false;
          // this.$message( {type : 'warning', message : '添加失败'} )
          // this.$message.warning(item)
        });
    },
    add() {
      this.addDialog.addForm = {}; // 清空因为点击过修改而绑定的数据
      this.addDialog.fileList = [];
      this.addDialog.title = "新增";
      this.addDialog.visible = true;
      this.selectTypes();
      this.selectDepartments();
      this.selectLevels();
      this.selectSecurities();
    },
    selectTypes() {
      this.addDialog.types = [];
      getAction(this.url.findAllType).then((resp) => {
        this.addDialog.types = resp.data;
      });
    },
    selectSecurities() {
      this.addDialog.securities = [];
      getAction(this.url.findAllSecurity).then((resp) => {
        this.addDialog.securities = resp.data;
      });
    },
    selectLevels() {
      this.addDialog.levels = [];
      getAction(this.url.findAllLevel).then((resp) => {
        this.addDialog.levels = resp.data;
      });
    },
    selectDepartments() {
      this.addDialog.departments = [];
      getAction(this.url.findAllDepartment).then((resp) => {
        this.addDialog.departments = resp.data;
      });
    },
    selectItemsExist(item) {
      this.addDialog.types = [];
      this.addDialog.securities = [];
      this.addDialog.levels = [];
      this.addDialog.departments = [];
      let requestUrl;
      if (item != null) {
        switch (item) {
          case "type":
            requestUrl = this.url.findAllTypeExist;
            break;
          case "security":
            requestUrl = this.url.findAllSecurityExist;
            break;
          case "level":
            requestUrl = this.url.findAllLevelExist;
            break;
          case "department":
            requestUrl = this.url.findAllDepartmentExist;
            break;
        }
        console.log(item);
        getAction(requestUrl).then((resp) => {
          this.addDialog.items = resp.data;
        });
        // .catch((e)=> {console.log(e)})
        // .finally(()=>{
        //   this.$message.warning("请求异常")
        // })
      } else {
        this.$message.warning("请求参数为null");
      }
    },
    addSubmit() {
      // 提交之前的表单验证，true表示通过
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        console.log(this.addDialog.addForm);
        this.addDialog.submitLoading = true;
        const fileList = this.addDialog.fileList.map((item) => {
          return {
            id: item.id,
            name: item.name,
            url: item.url,
            type: 8,
            operator: item.response.operator,
          };
        });
        let url = "";
        console.log(this.addDialog.addForm.id);
        if (
          this.addDialog.addForm.id != null &&
          this.addDialog.addForm.id != ""
        ) {
          // 如果表单中存在 id 表示进行的是修改操作
          url = this.url.updateDocument;
        } else {
          // 新增操作
          url = this.url.insertDocument;
        }
        postActionByJson(url, {
          document: this.addDialog.addForm,
          files: fileList,
        })
          .then((resp) => {
            this.$message.success("success");
            this.addDialog.addForm = {};
            this.addDialog.visible = false;
            this.toSearch();
          })
          .catch((item) => {
            //console.log(item);
            // this.$message( {type : 'warning', message : '添加失败'} )
            // this.$message.warning(item)
          })
          .finally(() => {
            this.addDialog.addForm = {};
            this.addDialog.fileList = [];
            this.addDialog.visible = false;
            this.toSearch();
          });
      });
    },
    updateDocumentStatus(scope) {
      let id = "";
      let status = "";
      if (scope != null) {
        id = scope.id;
        status = scope.status;
        console.log("before " + status);
        switch (status) {
          case 0:
            status = 1;
            break; // 0-表示未发文，则此操作一定是 发文操作
          case 1:
            status = 2;
            break; // 1-表示已发文，则此操作一定是 撤回操作
          case 2:
            status = 1;
            break; // 2-表示已撤回，则此操作一定是 发文操作
        }
        console.log("after " + status);
        postActionByQueryString(this.url.updateDocumentStatus, {
          id: id,
          status: status,
        }).then((resp) => {
          this.$message.success("success");
          this.toSearch();
        });
      } else {
        return this.$message.error("操作失败！");
      }
    },
    deleteDocument(scope) {
      let id = "";
      if (scope != null) {
        id = scope.id;
        postActionByQueryString(this.url.deleteDocument, { id: id }).then(
          (resp) => {
            this.$message.success("success");
            this.toSearch();
          }
        );
      } else {
        return this.$message.error("操作失败！");
      }
    },
    showUpdateDialog(scope, index) {
      this.addDialog.title = "修改";
      this.addDialog.addForm = scope;
      this.addDialog.closeFrom = scope;
      this.addDialog.fileList = [];
      this.uploadLoading[index] = true;
      this.selectTypes();
      this.selectDepartments();
      this.selectLevels();
      this.selectSecurities();
      /*  this.addDialog.addForm.type = this.addDialog.addForm.typeId
        this.addDialog.addForm.department = this.addDialog.addForm.departmentId
        this.addDialog.addForm.level = this.addDialog.addForm.levelId
        this.addDialog.addForm.security = this.addDialog.addForm.securityId*/
      this.addDialog.visible = true;
      getAction(this.url.selectFileByOtherId, { otherId: scope.id, type: 8 })
        .then((resp) => {
          resp.data.map((item) => {
            let response = item;
            response.error = 0;
            response.fileId = response.id;
            response.fileName = response.name;
            this.addDialog.fileList.push({
              uid: 0 - item.id,
              name: item.name,
              operator: item.operator,
              status: "done",
              response: response,
              url: response.url,
            });
          });
          this.uploadDialogVisible = true;
        })
        .finally(() => {
          this.uploadLoading[index] = false;
        });
    },
    dateTimeFormat,
    loadPools() {},
  },
};
</script>
<style lang="scss" scoped>
.el-card {
  height: 618px;
}
/deep/.el-card__body {
  padding-top: 10px;
  padding-left: 23px;
  padding-right: 23px;
}
</style>
